package com.ddiviewer;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;

public class AuthenticationDialog extends Activity {
	
	String				prefFileName;
	Button				loginInfoSubmit;
	EditText 			usernameEditText;
	EditText			passwordEditText;
	SharedPreferences	sp;
	InputMethodManager	keyboard;
	
	
	/*
	 * onCreate - Override
	 */
	@Override
	public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);        
        setContentView(R.layout.dialog);
        
        // Global Strings
        prefFileName = getResources().getString(R.string.prefFileName);
        
        // Set Up Editable Fields
		usernameEditText	= (EditText) findViewById(R.id.usernameEditText);
		passwordEditText	= (EditText) findViewById(R.id.passwordEditText);
		loginInfoSubmit		= (Button)   findViewById(R.id.loginInfoSubmit);
		keyboard 			= (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		
		SharedPreferences sp = getSharedPreferences(prefFileName, MODE_PRIVATE);
        
        // Populate info if it exists
        usernameEditText.setText(sp.getString("username", null));
        passwordEditText.setText(sp.getString("password", null));
        
        // click listener for button
        loginInfoSubmit.setOnClickListener(new Button.OnClickListener() {
        	
        	public void onClick(View v) {
        		commitDataAndClose();
        	}
        });
	}
	
	
	/*
	 * onKeyUp - Override
	 */
	@Override
	public boolean onKeyUp(int keyCode, KeyEvent event) {
		if ((keyCode == KeyEvent.KEYCODE_MENU)) {
			finish();
			return true;
		}
		return false;
	}

	/*
	 * commitDataAndClose - commit method
	 */
	public void commitDataAndClose() {
		try {
			SharedPreferences sp = getSharedPreferences(prefFileName, Context.MODE_PRIVATE);
	        SharedPreferences.Editor e = sp.edit();
	        
			e.putString("username", usernameEditText.getText().toString());
			e.putString("password", passwordEditText.getText().toString());
			e.commit();
			finish();
			
		} catch (Exception e) {
			Log.e("DDI_ERROR", e.getMessage());
		}
	}
}

